#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
pthread_mutex_t m_mutex;

pthread_mutex_t m_mutex_;
pthread_cond_t m_cond;
pthread_cond_t m_cond_;


pthread_t pthdr[10];

static int thread_state = 1;
static int g_dowork = 0;
static int threadEnd = 0;
int runflag = 0;
void *threadFunc1(void *argc)
{
	printf("[%u]get a lock!\n", *(long*)argc);
	pthread_cond_wait(&m_cond, &m_mutex);
	printf("[%u]waited\n",*(long*)argc);
	printf("a thread[%u] running\n", *(long*)argc);
	pthread_mutex_unlock(&m_mutex);
}

void *threadFunc2(void *argc)
{
	int i;
	static int n = 1;
	printf("thread function 2 is running!\n");
//	pthread_mutex_lock(&m_mutex);
	while(thread_state)
	{
		if(g_dowork==0)
		{
			pthread_mutex_lock(&m_mutex);
			printf("thread stop!\n");
			pthread_cond_wait(&m_cond, &m_mutex);
			g_dowork = 1;
			if(thread_state==1)
			{	
				printf("thread begin to run!\n");
			}
			pthread_cond_signal(&m_cond_);
			n = 1;
			
			pthread_mutex_unlock(&m_mutex);
		}
		else
		{
			runflag = 1;
			int time = 100000;
			while(time--);
			printf("do working!\n");
			if(n--==0){
				g_dowork  = 0;
			}
		}
	}
	printf("thread ended!\n");
	threadEnd = 1;
}

int main()
{
	pthread_cond_init(&m_cond, NULL);
	pthread_cond_init(&m_cond_, NULL);
	pthread_mutex_init(&m_mutex, NULL);
	pthread_mutex_init(&m_mutex_, NULL);

	//for(int i=0;i<1;i++)
	//{
		pthread_create(&pthdr[0], NULL, threadFunc2, (void*)&pthdr[0]);
		//pthread_mutex_lock(&m_mutex);
		//pthread_cond_signal(&m_cond);
	//}
	char c = 0;
	while(1)
	{
		printf("input a word:\n");
		scanf("%d",&c);
		printf("your word is:%d\n",c);
		if(c==1)
		{
			printf("get a lock\n");
			pthread_mutex_lock(&m_mutex_);
			printf("got a lock\n");
			pthread_cond_broadcast(&m_cond);
			printf("broadcast finish!\n");
			pthread_cond_wait(&m_cond_, &m_mutex_);
			printf("waited!\n");
			//while(g_dowork==0)
			//;
			while(runflag==0);
			if(runflag==1)
				printf("start succeed!\n");
			else
				printf("start failed!\n");
			runflag = 0;
			pthread_mutex_unlock(&m_mutex_);
		}
		else if(c==2)
		{
			g_dowork = 0;
			pthread_mutex_lock(&m_mutex_);
			pthread_cond_signal(&m_cond);
			printf("stop succeed!\n");
			pthread_mutex_unlock(&m_mutex_);
			
		}
		else if(c==3)
		{
			thread_state = 0;
			pthread_cond_signal(&m_cond);
			if(threadEnd == 1)
			{		
				printf("end thread succeed!\n");
				break;	
			}
		}
	}
	char ret;
	void *_ret = (void*)&ret;
	for(int i=0;i<1;i++)
	{
		//pthread_cond_broadcast(&m_cond);
		pthread_join(pthdr[i], &_ret);
		printf("thread out data is:%d\n", ret);
	}
	printf("all thread is out!\n");
}
